import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import * as SearchAction from '../actions/search'
import forEach from 'lodash/forEach'
import isEmpty from 'lodash/isEmpty'

 import WeaFormmodeTop from './WeaFormmodeTop'
 import AddCustomerShare from './setting/AddCustomerShare'
 import CrmTools from './crmTools';

 import * as Operate from '../util/Operate'

import { WeaTable } from 'comsRedux'

const WeaTableAction = WeaTable.action;

import {
    WeaTop,
    WeaTab,
    WeaLeftRightLayout,
    WeaSearchGroup,
    WeaRightMenu,
    WeaPopoverHrm,
    WeaBrowser,
    WeaDialog,
    WeaSelect,
    WeaInput 
} from 'ecCom'

import {WeaErrorPage,WeaTools,WeaAlertPage} from 'ecCom'
// const { getComponent } = WeaTools;

import {Button,Form,Modal,message,Row,Col,Spin} from 'antd' 
const createForm = Form.create;
const FormItem = Form.Item;

import cloneDeep from 'lodash/cloneDeep'
import objectAssign from 'object-assign'

import PropTypes from 'react-router/lib/PropTypes'
import Immutable from 'immutable'
const is = Immutable.is;

let _this = null;

class Search extends React.Component {
    constructor(props) {
		super(props);
        _this = this;
        this.state={
            showModal:false
        }
    }
    componentDidMount() {
         const {actions,location:{query}} = this.props;
        //search 查询客户  monitor 客户监控  assign 客户分配  share 批量共享
         actions.setNowRouterCmpath('searchResult');
         actions.getTitleInfo({selectType:query.type});
         actions.doSearch({selectType:query.type});
         actions.initDatas({selectType:query.type});
    }
    componentWillReceiveProps(nextProps) {
        const keyOld = this.props.location.key;
        const keyNew = nextProps.location.key;
        const {query} = nextProps.location;
        if(keyOld!==keyNew) {
            const {actions} = this.props;
            
            actions.getTitleInfo({selectType:query.type});
            actions.doSearch({selectType:query.type});
            actions.initDatas({selectType:query.type});
        }
    }
    shouldComponentUpdate(nextProps,nextState) {
        return !is(this.props.title,nextProps.title)||
        !is(this.props.topButtons,nextProps.topButtons)||
        !is(this.props.dataKey,nextProps.dataKey)||
        !is(this.props.conditioninfo,nextProps.conditioninfo)||
        !is(this.props.showSearchAd,nextProps.showSearchAd)||
        !is(this.props.searchParamsAd,nextProps.searchParamsAd)||
        !is(this.props.comsWeaTable,nextProps.comsWeaTable)||
        !is(this.props.orderFields,nextProps.orderFields)||
        !is(this.props.loading,nextProps.loading)||
        !is(this.props.hasright,nextProps.hasright)||
        !is(this.props.rcList,nextProps.rcList)||
        !is(this.props.paramsBase,nextProps.paramsBase)||
        !is(this.state.showModal,nextState.showModal)||
        !is(this.props.customerStr,nextProps.customerStr)||
        !is(this.props.customerIds,nextProps.customerIds);
    }
    componentWillUnmount(){
    	// const {actions,isClearNowPageStatus} = this.props;
        // actions.unmountClear(isClearNowPageStatus);
        // actions.isClearNowPageStatus(false);
    }
    render() {
        let that = this;
        const {loading,comsWeaTable,actions,title,dataKey,showSearchAd,searchParamsAd,hasright,paramsBase,customerStr,customerIds} = this.props;
        const {showModal} =this.state;
        const {getFieldProps} = this.props.form;
        const name = dataKey ? dataKey.split('_')[0] : 'init';
        const loadingTable = comsWeaTable.get(name).toJS().loading;
        const selectedRowKeys = comsWeaTable.get('selectedRowKeys');
        const formItemLayout = {
            labelCol: { span: 6 },
            wrapperCol: { span: 16 },
        };
        if(hasright == "-1"){
            return (
				<div className="align-center top40">
					<Spin size="large"></Spin>
				</div>);
        }else if(!hasright){
            return (
                <WeaAlertPage>
                    <div className="color-black">
                        对不起，您暂时没有权限
                    </div>
                </WeaAlertPage>);
        }else {
            return (
                <div className="crm-top-req">
                    { <WeaPopoverHrm />}
                    <WeaRightMenu datas={this.getRightMenu()} onClick={this.onRightMenuClick.bind(this)}>
                        <WeaFormmodeTop 
                            title={title}
                            loading={loading || loadingTable}
                            icon={<i className='icon-coms-crm' />}
                            iconBgcolor='#96358a'
                            buttons={this.getButtons()}
                            buttonSpace={10}
                            showDropIcon={true}  
                            dropMenuDatas={this.getRightMenu()}
                            onDropMenuClick={this.onRightMenuClick.bind(this)}
                            buttonsAd={this.getTabButtonsAd()}  //高级搜索底部button
                            searchType={['base','advanced']}
                            searchsBaseValue={searchParamsAd.get('name')}  //外部inpt默认初始值
                            setShowSearchAd={bool=>{actions.setShowSearchAd(bool)}}
                            hideSearchAd={()=> actions.setShowSearchAd(false)}
                            searchsAd={<Form horizontal>{this.getSearchs()}</Form>}
                            showSearchAd={showSearchAd}
                            onSearch={v=>{actions.doSearch()}}
                            onSearchChange={v=>{actions.saveOrderFields({name:{name:'name',value:v}})}}
                        >
                            <WeaTable 
                                sessionkey={dataKey}
                                hasOrder={true}
                                needScroll={true}
                                onOperatesClick={this.onOperatesClick.bind(this)}
                            />
                        </WeaFormmodeTop>
                    </WeaRightMenu> 
                    {
                    paramsBase.get('selectType') == "assign" || paramsBase.get('selectType') == "monitor"  ?
                        <WeaDialog title={paramsBase.get('selectType') == "assign" ? "分配客户经理" :"修改经理"} icon="icon-coms-crm" iconBgcolor="#6d3cf7" visible={showModal} style={{width: 520, height: 150}} 
                            buttons={[
                                <Button type="primary"  onClick={()=>this.doSave(paramsBase.get('selectType'))} >保存</Button>,
                                <Button onClick={() => this.setState({showModal:false})}>关闭</Button>
                            ]} 
                            onCancel={() => this.setState({showModal:false})}>	
                            {<div className="crm-customer-assign">
                                <Form horizontal>
                                {
                                    paramsBase.get('selectType') == "assign" &&
                                    <FormItem
                                    {...formItemLayout}
                                    label="客户名称："
                                    >
                                    <WeaInput  {...getFieldProps('customerIds', { initialValue: customerIds })} viewAttr={1} value={customerStr} />
                                    </FormItem>
                                }
                                {
                                    paramsBase.get('selectType') == "assign" &&
                                    <FormItem
                                    {...formItemLayout}
                                    label="客户经理："
                                    >
                                    <WeaBrowser {...getFieldProps('manager')}  type={1}  viewAttr={3} title={"人员"} />
                                    </FormItem>
                                }  
                                {
                                    paramsBase.get('selectType') == "monitor" &&
                                    <FormItem
                                    {...formItemLayout}
                                    label="对象类型："
                                    >
                                    <WeaSelect style={{width:"150px"}}   viewAttr={2} value={`${1}`} options={[{"key": "1","selected": true,"showname": "人力资源"}]} />
                                    </FormItem>
                                } 
                                {
                                    paramsBase.get('selectType') == "monitor" &&
                                    <FormItem
                                    {...formItemLayout}
                                    label="对象："
                                    >
                                    <WeaBrowser {...getFieldProps('relatedShareId')}  type={1}  viewAttr={3} title={"人员"} />
                                    </FormItem>
                                }     
                                </Form>
                            </div>
                            }
                        </WeaDialog>   :""
                    } 
                    {
                        paramsBase.get('selectType') == "share" || paramsBase.get('selectType') == "monitor"  ?
                        <AddCustomerShare  ref="addCustomerShare" all={this.props} customerIds={customerIds} actions={actions}/>:""
                    }
                </div>
            )
        }
    }
    getRightMenu(){
    	const {comsWeaTable,actions,rcList,dataKey} = this.props;
        const tablekey = dataKey ? dataKey.split('_')[0] : 'init';
		const tableNow = comsWeaTable.get(tablekey);
    	const selectedRowKeys = tableNow.get('selectedRowKeys');
    	let _disabled =!(selectedRowKeys && `${selectedRowKeys.toJS()}`);
        let btnArr = [];
        rcList && !is(rcList,Immutable.fromJS([])) && rcList.map(m=>{
            btnArr.push({
                icon: <i className={m.get('menuIcon')} />,
                content: m.get('menuName'),
                disabled : m.get("isControl") == "1" && _disabled
            })
        });
    	return btnArr
    }
    onRightMenuClick(key){
        const {actions,comsWeaTable,dataKey,rcList} = this.props;
        const tablekey = dataKey ? dataKey.split('_')[0] : 'init';
        const tableNow = comsWeaTable.get(tablekey);
    	const selectedRowKeys = tableNow.get('selectedRowKeys');
        let that = this;
        rcList && !is(rcList,Immutable.fromJS([])) && rcList.map((m,i)=>{
        	if(Number(key) == i){
        		let fn = m.get('menuFun').indexOf('this') >= 0 ? `${m.get('menuFun').split('this')[0]})` : m.get('menuFun');
        		if(fn == ""){
        			if(m.get('type') == "BTN_SEARCH"){ //搜索
        				actions.doSearch();
        			}else if(m.get('type') == "BTN_COLUMN"){ //定制列
                        actions.setColSetVisible(dataKey,true);
                        actions.tableColSet(dataKey,true)
        			}else if(m.get('type') == "BTN_ASSIGN"){ //分配客户经理
                        that.setState({showModal:true});
                        actions.getCrmNamesById({customerIds:`${selectedRowKeys.toJS()}`});
        			}else if(m.get('type') == "BTN_CHANGEMANAGER"){ //修改经理
                        that.setState({showModal:true});
                        actions.getCustomerIds(`${selectedRowKeys.toJS()}`);
        			}else if(m.get('type') =='BTN_SHAREBATCH'){   //批量共享
                        that.refs.addCustomerShare.visible = true;
                        actions.getCustomerIds(`${selectedRowKeys.toJS()}`);
                    }
        		}else{
                    fn = Operate.fnJoinPara(fn);
	        		if(selectedRowKeys){
	        			var ids = "";
	        			selectedRowKeys.toJS().map((id)=>{
	        				ids += "," + id;
	        			});
	        			ids = ids.length > 0 ? ids.substring(1) : ids;

	        			fn = Operate.fnJoinPara(fn,ids);
	        		}

	        		eval("Operate." + fn);
        		}
        	}
        });
   }
     getSearchs() {
    	const { conditioninfo } = this.props;
		let group = [];
		conditioninfo.toJS().map(c =>{
			let items = [];
			c.items.map(field => {
                    items.push({
                        com:(<FormItem
                            label={`${field.label}`}
                            labelCol={{span: `${field.labelcol}`}}
                            wrapperCol={{span: `${field.fieldcol}`}}>
                                { WeaTools.getComponent(field.formItemType, field.browserConditionParam, field.domkey, this.props, field)}
                            </FormItem>),
                        colSpan:1
                    })
                });
			group.push(<WeaSearchGroup needTigger={true} title={c.title} showGroup={c.defaultshow} items={items} />)
		});
		return group
    }
   
    getTabButtonsAd() {
    	const {actions,location:{query}} = this.props;
        return [
            (<Button type="primary" onClick={()=>{actions.doSearch();actions.setShowSearchAd(false)}}>搜索</Button>),
            (<Button type="ghost" onClick={()=>{actions.saveOrderFields({})}}>重置</Button>),
            (<Button type="ghost" onClick={()=>{actions.setShowSearchAd(false)}}>取消</Button>)
        ]
    }
     getButtons() {
         const {comsWeaTable,topButtons,dataKey,actions,rcList} = this.props;
         const tablekey = dataKey ? dataKey.split('_')[0] : 'init';
         const tableNow = comsWeaTable.get(tablekey);
         const selectedRowKeys = tableNow.get('selectedRowKeys');
        let btnArr = [];
        let that = this;
        const isDisabled = !(selectedRowKeys && `${selectedRowKeys.toJS()}`);
        rcList && !is(rcList,Immutable.fromJS({})) && rcList.map(m=>{
            let fn = m.get('menuFun').indexOf('this') >= 0 ? `${m.get('menuFun').split('this')[0]})` : m.get('menuFun');
            m.get('isTop') == '1' && btnArr.length < 4 && btnArr.push(
            	<Button type="primary" 
            		disabled={isDisabled && m.get("isControl") == "1"}
            		onClick={()=>{
                        if(fn == ""){
                            if(m.get('type') == "BTN_SEARCH"){ //搜索
                                actions.doSearch();
                            }else if(m.get('type') == "BTN_COLUMN"){ //定制列
                                actions.setColSetVisible(dataKey,true);
                                actions.tableColSet(dataKey,true)
                            }else if(m.get('type') == "BTN_ASSIGN"){ //分配客户经理
                                that.setState({showModal:true});

                                actions.getCrmNamesById({customerIds:`${selectedRowKeys.toJS()}`});
                            }else if(m.get('type') == "BTN_CHANGEMANAGER"){ //修改经理
                                that.setState({showModal:true});
                                actions.getCustomerIds(`${selectedRowKeys.toJS()}`);
                            }else if(m.get('type') =='BTN_SHAREBATCH'){   //批量共享
                                that.refs.addCustomerShare.visible = true;
                                actions.getCustomerIds(`${selectedRowKeys.toJS()}`);
                            }
                        }else{
                            if(selectedRowKeys){
                                var ids = "";
                                selectedRowKeys.toJS().map((id)=>{
                                    ids += "," + id;
                                });
                                ids = ids.length > 0 ? ids.substring(1) : ids;
                                fn = Operate.fnJoinPara(fn);
                                fn = Operate.fnJoinPara(fn,ids);
                            }
                            eval("Operate." + fn);	
                        }
            		}}>
            		{m.get('menuName')}
            	</Button>
            );
        });
        return btnArr;
    }
    onOperatesClick=(record,index,operate,flag)=>{
       // console.log(record,index,operate,flag)

		// let _href = operate && operate.href ? operate.href : "";
		// let fn = _href.replace("javascript:","");
		// if(fn != ""){
		// 	fn = Operate.fnJoinPara(fn,'Dummy');
		// 	fn = Operate.fnJoinPara(fn,dummyId);
		// 	fn = Operate.fnJoinPara(fn,record.id);
		// }
		// eval("Operate." + fn);

	}
    doSave=(type)=>{
        const {actions,location:{query},customerIds} = this.props;
        const {getFieldValue,resetFields} = this.props.form;
        if(type=="assign"){
            const params = {
                customerIds:getFieldValue('customerIds'),
                manager:getFieldValue('manager')
            }
            if(params.manager){
                actions.saveCustomerAssign(params,query);
                this.setState({showModal:false})
            }else{
                Modal.warning({
                    title: '系统提示',
                    content: '必填信息不完整!',
                });
            }
        }else if(type == "monitor"){
            const params = {
                customerIds:customerIds,
                relatedShareId:getFieldValue('relatedShareId')
            }
            if(params.relatedShareId){
                actions.saveChangeManager(params,query);
                this.setState({showModal:false})
            }else{
                Modal.warning({
                    title: '系统提示',
                    content: '必填信息不完整!',
                });
            }
        }
    }

}


class MyErrorHandler extends React.Component {
    render(){
        const hasErrorMsg = this.props.error && this.props.error!=="";
        return (
            <WeaErrorPage msg={hasErrorMsg?this.props.error:"对不起，该页面异常，请联系管理员！"} />
        );
    }
}

Search = WeaTools.tryCatch(React, MyErrorHandler, {error: ""})(Search);

Search = createForm({
	onFieldsChange(props, fields) {
        props.actions.saveOrderFields({...props.orderFields.toJS(), ...fields});
    },
	mapPropsToFields(props) {
		return props.orderFields.toJS();
  	}
})(Search);

function mapStateToProps(state) {
	const {crmsearchResult,comsWeaTable} = state;
    return {
    	loading: crmsearchResult.get('loading'),
        title: crmsearchResult.get('title'),
         topButtons: crmsearchResult.get('topButtons'),
         dataKey: crmsearchResult.get('dataKey'),
         conditioninfo: crmsearchResult.get('conditioninfo'),
         showSearchAd: crmsearchResult.get('showSearchAd'),
        searchParamsAd: crmsearchResult.get('searchParamsAd'),
        orderFields:crmsearchResult.get('orderFields'),
        hasright:crmsearchResult.get('hasright'),
        rcList:crmsearchResult.get('rcList'),
        paramsBase:crmsearchResult.get('paramsBase'),
        customerStr:crmsearchResult.get('customerStr'),
        customerIds:crmsearchResult.get('customerIds'),
		//table
        comsWeaTable: comsWeaTable, //绑定整个table
    }
}

function mapDispatchToProps(dispatch) {
    return {
        actions: bindActionCreators({...SearchAction,...WeaTableAction}, dispatch)
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(Search);
